package com.xpffly.springboot.config.db.hikari;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @Author: xpengfei
 * @Date: 2020/11/30 16:30
 * @Description：配置mybatis
 */
//@Configuration
public class HikariSessionFactoryConfig {

    private static final String MIS_PACKAGE = "com.icbc.assisticbc.repository.oracle.mis";
    private static final String AOMDB_PACKAGE = "com.icbc.assisticbc.repository.mysql.aomdb";
    private static final String MIS = "misSqlSessionFactory";
    private static final String AOMDB = "aomdbSqlSessionFactory";
    private static final String MAPPER_LOCATION = "classpath:mapper/*.xml";

    @Bean(name = MIS)
    public SqlSessionFactory misSqlSessionFactory(@Qualifier("misDataSource") DataSource dataSource) throws Exception {
        return getSqlSessionFactory(dataSource);
    }

    @Bean(name = AOMDB)
    public SqlSessionFactory aomdbSqlSessionFactory(@Qualifier("aomdbDatasource") DataSource dataSource)
            throws Exception {
        return getSqlSessionFactory(dataSource);
    }

    @Bean
    public MapperScannerConfigurer misScannerConfigurer() {
        return getMapperScannerConfigurer(MIS_PACKAGE, MIS);
    }

    @Bean
    public MapperScannerConfigurer aomdbScannerConfigurer() {
        return getMapperScannerConfigurer(AOMDB_PACKAGE, AOMDB);
    }

    /**
     * 构造scanMapper
     *
     * @param mapsPackage
     * @param sqlsessionfactory
     * @return
     */
    private MapperScannerConfigurer getMapperScannerConfigurer(String mapsPackage, String sqlsessionfactory) {
        MapperScannerConfigurer config = new MapperScannerConfigurer();
        config.setBasePackage(mapsPackage);
        config.setSqlSessionFactoryBeanName(sqlsessionfactory);
        return config;
    }

    /**
     * 获取sessionFactory
     *
     * @param dataSource
     * @return
     * @throws Exception
     */
    private SqlSessionFactory getSqlSessionFactory(DataSource dataSource) throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
